<!-- views/system/Profile.vue -->
<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
        </div>
      </template>
      
      <el-form 
        :model="profileForm" 
        :rules="profileRules" 
        ref="profileFormRef"
        label-width="100px"
      >
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarUpload"
          >
            <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
            <el-avatar v-else :size="80" :src="profileForm.avatar">{{ userInitials }}</el-avatar>
          </el-upload>
          <div class="avatar-tip">点击头像上传新头像</div>
        </el-form-item>
        
        <el-form-item label="用户名" prop="name">
          <el-input v-model="profileForm.name" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" disabled />
          <div class="form-tip">邮箱不可更改</div>
        </el-form-item>
        
        <el-form-item label="角色">
          <el-tag v-if="currentUserRole">{{ currentUserRole }}</el-tag>
        </el-form-item>
        
        <el-form-item label="加入时间">
          <span>{{ formatDate(profileForm.createdAt) }}</span>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="updateProfile"
            :loading="saving"
          >
            保存资料
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>
      
      <el-form 
        :model="passwordForm" 
        :rules="passwordRules" 
        ref="passwordFormRef"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input 
            v-model="passwordForm.currentPassword" 
            type="password"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="changePassword"
            :loading="changingPassword"
          >
            修改密码
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
// @ts-ignore
import { ref, reactive, computed, onMounted } from '@vue/runtime-core'
// @ts-ignore
import { ElMessage } from 'element-plus'
import { useAppStore } from '@/stores/appStore'

// Store
const appStore = useAppStore()

// 响应式数据
const profileFormRef = ref()
const passwordFormRef = ref()
const saving = ref(false)
const changingPassword = ref(false)

// 表单数据
const profileForm = reactive({
  name: '',
  email: '',
  avatar: '',
  createdAt: ''
})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { 
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const userInitials = computed(() => {
  const name = profileForm.name || 'U'
  return name.charAt(0).toUpperCase()
})

const currentUserRole = computed(() => {
  // 简化处理，实际应该从用户信息中获取角色
  return appStore.user?.role === 'admin' ? '管理员' : '普通用户'
})

// 方法
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  
  return isJPG && isLt2M
}

const handleAvatarUpload = (options: any) => {
  // 模拟上传头像
  const { file } = options
  const reader = new FileReader()
  reader.onload = (e) => {
    profileForm.avatar = e.target?.result as string
    ElMessage.success('头像上传成功')
  }
  reader.readAsDataURL(file)
}

const updateProfile = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      saving.value = true
      try {
        // 模拟保存资料
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 更新应用状态
        appStore.setCurrentUser({
          ...appStore.user,
          name: profileForm.name
        })
        
        ElMessage.success('资料保存成功')
      } catch (error) {
        console.error('保存资料失败:', error)
        ElMessage.error('保存资料失败: ' + (error as Error).message)
      } finally {
        saving.value = false
      }
    }
  })
}

const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      changingPassword.value = true
      try {
        // 模拟修改密码
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        ElMessage.success('密码修改成功')
        
        // 重置表单
        passwordForm.currentPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败: ' + (error as Error).message)
      } finally {
        changingPassword.value = false
      }
    }
  })
}

const loadUserProfile = () => {
  // 从应用状态加载用户信息
  if (appStore.user) {
    profileForm.name = appStore.user.name || ''
    profileForm.email = appStore.user.email || ''
    profileForm.avatar = appStore.user.avatar || ''
    profileForm.createdAt = appStore.user.createdAt || ''
  }
}

// 生命周期
onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card,
.password-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
}

.avatar-uploader {
  display: block;
  margin-bottom: 10px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.avatar-tip {
  font-size: 12px;
  color: #999;
  text-align: center;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>